#include "ResourceManager.h"
#include "tinyxml2.h"
#include <iostream>

typedef tinyxml2::XMLDocument XMLDocument;
typedef tinyxml2::XMLElement XMLElement;

template<typename R>
ResourceManager<R>::ResourceManager(R* (*getResource) (const char*), void(*deleteResource) (R*), std::string resourceName)
{
	m_getResource = getResource;
	m_deleteResource = deleteResource;
	m_resourceName = resourceName;
}

template<typename R>
bool ResourceManager<R>::loadResources()
{
	XMLDocument resourceInfo;
	if (resourceInfo.LoadFile("resources.xml") != 0)
	{
		std::cout << "Error: Could not find XML document.";
		return false;
	}

	std::string resourceDirectory = 
		resourceInfo.FirstChild()->
		FirstChildElement(m_resourceName + "s")->
		FirstChildElement(m_resourceName + "-directory")->
		GetText();

	XMLElement *element = 
		resourceInfo.FirstChild()->
		FirstChildElement(m_resourceName + "s")->
		FirstChildElement(m_resourceName);

	do
	{
		std::string id = element->FirstChildElement("id")->GetText();
		std::string filename = element->FirstChildElement("filename")->GetText();

		std::string URI = resourceDirectory + filename;
		
		R *resource = m_getResource((URI).c_str());

		if (!resource)
		{
			std::cout << "Couldn't load " + m_resourceName + " file" << std::endl;
			return false;
		}

		std::cout << "Loaded image: " << id << " -> " << filename << std::endl;

		m_resourceMap[id] = resource;

	} while (element = element->NextSiblingElement());

	return true;
}

template<typename R>
void ResourceManager<R>::deleteResources()
{
	for (auto i = m_resourceMap.begin(); i != m_resourceMap.end(); i = ++i)
	{
		m_deleteResource((*i).second);
		(*i).second = NULL;
	}
}

template<typename R>
R* ResourceManager<R>::get(std::string id) const
{
	auto temp = m_resourceMap.find(id);
	if (temp == m_resourceMap.end())
		return NULL;
	else
		return temp->second;
}